Eine Übersicht über gängige Basis-Funktionen bietet der BaseR-CheatSheet: http://github.com/rstudio/cheatsheets/raw/master/base-r.pdf
2+2
## [1] 4
4*3
## [1] 12
12.5/pi
## [1] 3.978874
3^5
## [1] 243
2+3*6
## [1] 20
(2+3)*6
## [1] 30
x <- 5
y <- 12
x+y
## [1] 17
x*y
## [1] 60
z <- x+y
z
## [1] 17
l1 <- c(x^1,x^2,x^3,x^4,x^5)
l2 <- c(y*1,y*2,y*3,y*4,y*5)
l1 + l2
## [1] 17 49 161 673 3185
Eine Funktion bereits gesehen. “c()” Funktionen sind bereits vorgefertigte “Miniprogramme”, manchmal aber auch sehr einfache, die mit einem bestimmten Objekt etwas bestimmtes tun.
Bsp: c(): Concatenate = Verknüpfen: Die Elemente innerhalb der Klammer, werden miteinander kombiniert und zu einem Vektor zusammengefasst.
Andere Beispiele sind bestimmte mathematische Funktionen, wie Mittelwert oder Standardabweichung. Beinahe alles in R wird durch Funktionen erledigt. Eine Funktion ist immer zusammen gesetzt aus dem Namen und den Eingabeparametern innerhalb von Klammern. Gibt es keine Eingabeparameter wird die Klammer leer - aber nicht weg - gelassen.
summary(l1)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 5 25 125 781 625 3125
var(l1)
## [1] 1780680
sd(l1)
## [1] 1334.421
sum(l1)
## [1] 3905
mean(l2)
## [1] 36
round(3.63545234123, digits = 4)
## [1] 3.6355
plot(l1)
plot(c(5,25,2123,123,5345),l2)
In R können auch ganz einfach eigene Funktionen geschrieben werden. Hilfe gibt es hier: https://www.datacamp.com/community/tutorials/functions-in-r-a-tutorial Zu allen Funktionen gibt es eine Hilfe, welche die möglichen Optionen (arguments) und die grundsätzliche Funktionsweise der Funktion beschreibt. ACHTUNG: Ohne Klammern hinter der Funktion, über die man Infos haben will.
help(sd)
?sd
?summary
Bisher hatten wir nur Zahlen in unseren Beispielen. In R ist es aber auch möglich (und meistens unproblematisch) mit anderen Datentypen - wie bspw. Text oder Ja/Nein-Zuständen - zu arbeiten.
Inhalte mit Text wird meist in Anführungsstriche oder Hochkommata gesetzt. Die Klasse dieses Objekts ist dann automatisch character
txt <- "Das ist ein Text"
txt
## [1] "Das ist ein Text"
class(txt)
## [1] "character"
Manchmal bietet es sich an nur “Wahr” oder “Falsch” als eigenen Datentypen zu nutzen. Die Schlüsselwörter hier sind TRUE und FALSE. Immer das ganze Wort großgeschrieben. Oftmals wird diese Klasse dafür genutzt Zustände abzufragen, bspw. ob etwas größer ist, ob der Inhalt übereinstimmt etc:
WAHRODERFALSCH <- FALSE
class(WAHRODERFALSCH)
## [1] "logical"
isTRUE(WAHRODERFALSCH)
## [1] FALSE
3 > 5
## [1] FALSE
ist3groesser5 <- 3 > 5
"Ist das ein Text" == txt
## [1] FALSE
Zurück zu Zahlen: Bei Zahlen in R gibt es Unterschiede, ob die Zahl eine “Ganzzahl” (integer) oder eine Zahl mit Nachkommastellen (numeric) ist. Normalerweise ist der Unterschied in R egal und mann kann mit beiden Typen identisch arbeiten. Es kann aber Fälle geben, in denen man den Typ bewusst ändern muss.
is.integer(3.541)
## [1] FALSE
is.integer(3)
## [1] FALSE
class(3)
## [1] "numeric"
integer3 <- as.integer(3)
is.integer(integer3)
## [1] TRUE
class(3.654)
## [1] "numeric"
Bei der Arbeit mit Surveys kommen außerdem häufig noch factors for. Faktoren werden verwendet, um kategorische Daten darzustellen. Faktoren können geordnet oder ungeordnet sein und sind eine wichtige Klasse für statistische Analysen und zum Plotten.
Faktoren werden als Ganzzahlen gespeichert und diesen eindeutigen Ganzzahlen sind Beschriftungen zugeordnet. Während Faktoren wie Zeichenvektoren aussehen (und sich oft verhalten), sind sie tatsächlich in Wirklichkeit ganze Zahlen. Manchmal führt das zu Problemen, wenn man sie wie strings/character behandelt.
education <- factor(c("low", "high", "medium", "high", "low", "medium", "high"))
levels(education)
## [1] "high" "low" "medium"
education
## [1] low high medium high low medium high
## Levels: high low medium
education <- factor(education, levels = c("low", "medium", "high"))
levels(education)
## [1] "low" "medium" "high"
min(education) # doesn't work
## Error in Summary.factor(structure(c(1L, 3L, 2L, 3L, 1L, 2L, 3L), .Label = c("low", : 'min' not meaningful for factors
education <- factor(education, levels = c("low", "medium", "high"), ordered = TRUE)
levels(education)
## [1] "low" "medium" "high"
min(education) # works!
## [1] low
## Levels: low < medium < high
Fügt man unterschiedliche Datentypen zusammen, so ist der Unterschied zwischen einer matrix und einem data.frame wichtig (siehe nächstes Kapitel). Während in einer matrix nur Elemente des gleichen Datentyps vorhanden sein können, sind bei einem data.frame auch unterschiedliche erlaubt.
numbers <- c(1,2,31,43,5,16)
txt <- c("a","b","oma","uni","zwei Wörter","z")
logical <- c(FALSE,TRUE,FALSE,FALSE,TRUE,FALSE)
factors <- factor(c("low", "high", "medium", "high", "low", "medium"))
tabelle <- cbind(numbers,txt,logical,factors)
## zum verbinden von Spalten (column-bind); zum verbinden von Zeilen rbind() (row-bind)
tabelle #Man sieht, alle Datentypen wurden zu "Texten" gemacht. Anführungsstriche sind um die Werte herum.
## numbers txt logical factors
## [1,] "1" "a" "FALSE" "2"
## [2,] "2" "b" "TRUE" "1"
## [3,] "31" "oma" "FALSE" "3"
## [4,] "43" "uni" "FALSE" "1"
## [5,] "5" "zwei Wörter" "TRUE" "2"
## [6,] "16" "z" "FALSE" "3"
class(tabelle) # R hat die Tabelle automatisch zur Matrix gemacht und deshalb alle Datentypen "gleich" gemacht.
## [1] "matrix"
tabelle2 <- data.frame(numbers,txt,logical,factors, stringsAsFactors = FALSE)
tabelle2
## numbers txt logical factors
## 1 1 a FALSE low
## 2 2 b TRUE high
## 3 31 oma FALSE medium
## 4 43 uni FALSE high
## 5 5 zwei Wörter TRUE low
## 6 16 z FALSE medium
class(tabelle2)
## [1] "data.frame"
class(tabelle2$txt)
## [1] "character"
class(tabelle2$numbers)
## [1] "numeric"
# Im Data.frame, sind alle Datentypen erhalten.
Normalerweise haben wir als Sozialwissenschaftler aber selten einzelne Rechnungen oder Vektoren sondern Tabellen mit Zeilen als Beobachtungen und Spalten als Variablen. Diese werden in R als Data Frames dargestellt (oder als Matrix, aber mit dataframes ist es meistens einfacher zu arbeiten).
data.frame(l1,l2)
## l1 l2
## 1 5 12
## 2 25 24
## 3 125 36
## 4 625 48
## 5 3125 60
df <- data.frame(l1,l2)
Einzelne Elemente des df lassen sich über eckige Klammern hinter dem Objektnamen auswählen. Dabei ist die erste Zahl die Nummer der Zeile und die zweite Zahl die Nummer der Spalte. Durch weglassen einer Zahl, wird entweder die ganze Zeile oder die ganze Spalte ausgegeben.
df[3,2]
## [1] 36
df[ ,2]
## [1] 12 24 36 48 60
df[3, ]
## l1 l2
## 3 125 36
df[4,5]
## NULL
Variablen (Spalten) lassen sich auch durch den Namen anwählen, indem hinter den Objektnamen ein $ geschrieben wird. RStudio schlägt einem dann meist sogar eine Liste vor, aus der man auswählen kann. Wiederrum kann man durch eckige Klammern, einzelne oder mehrere Elemente auswählen.
summary(df)
## l1 l2
## Min. : 5 Min. :12
## 1st Qu.: 25 1st Qu.:24
## Median : 125 Median :36
## Mean : 781 Mean :36
## 3rd Qu.: 625 3rd Qu.:48
## Max. :3125 Max. :60
summary(df$l1)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 5 25 125 781 625 3125
df$l2
## [1] 12 24 36 48 60
df$l1[3]
## [1] 125
df$l2[4]
## [1] 48
df$l1[1:3]
## [1] 5 25 125
df$l1[1:2]
## [1] 5 25
df$l1[c(3,5)]
## [1] 125 3125
Durch logische Operatoren lassen sich so bestimmte Zeilen suchen/ausschließen. So könnte man beispielsweise einen Datensatz mit mehreren Ländern so bearbeiten, dass am Ende nur ein Land heraus käme. Oder nur Menschen über 55 Jahre im Datensatz enthalten sind etc.
df
## l1 l2
## 1 5 12
## 2 25 24
## 3 125 36
## 4 625 48
## 5 3125 60
df[df$l1>100, ]
## l1 l2
## 3 125 36
## 4 625 48
## 5 3125 60
Gesprochen: Der Datensatz df und alle Spalten (Hinter dem Komma ist leer). Aber nur die Zeilen, wo in Spalte 1 (l1) Werte über 100 stehen.
Im Arbeitsverzeichnis liegen alle Dateien und Materialien. Das Arbeitsverzeichnis lässt sich auch über den Explorer etc. auf dem Computer, ganz normal über die Ordnerstruktur einsehen.
In R kann man sich sowohl den Pfad zum aktuellen Arbeitsverzeichnis anzeigen lassen:
getwd()
Oder einen anderen Pfad als Arbeitsverzeichnis setzen:
setwd('C://file/path')
Den Inhalt des Arbeitsverzeichnis kann man über dir() anzeigen lassen:
dir()
ls()
rm(list = ls())
Das Arbeitsverzeichnis beinhaltet “reale” Dateien. In der Arbeitsumgebung finden sich die Objekte der aktuellen R-Sitzung. Diese sind aber nur im Arbeitsspeicher und nicht tatsächlich auf der Festplatte gespeichert.
Einsehen kann man die aktuellen Objekte entweder direkt in R-Studio (meistens oben rechts unter “Environment”) oder über die Funktion ls():
ls()
## [1] "df" "education" "factors" "integer3"
## [5] "ist3groesser5" "l1" "l2" "logical"
## [9] "numbers" "tabelle" "tabelle2" "txt"
## [13] "WAHRODERFALSCH" "x" "y" "z"
Die einfachste Art Daten einzulesen ist, wenn sie als einfach “Text-Datei” vorliegen. Beispielsweise .CSV (comma-separated-values), oder anderweitige Formate mit einem eindeutigen Symbol als Trennzeichen für Spalten.
Aber auch andere Formate lassen sich in R einlesen, nur braucht man hierzu meistens zusätzliche Pakete und Funktionen.
Im amerikanischen Raum wird die csv-Datei mit Kommata als Spaltentrennzeichen und dem Punkt als Dezimalzeichen bei Zahlen verwendet. Im europäischen Raum wird meistens das Semikolon als Spaltentrennzeichen und das Komma als Dezimalzeichen genutzt. In R wurden deshalb 2 Arten von CSV-Einlese-Funktionen implementiert. read.csv für den amerikanischen Raum und read.csv2 für den europäischen. Die Funktionen lassen sich aber über die Optionen (arguments) anpassen.
read.csv(file = "datensatz_grades.csv", sep = ";", dec = ",")
## id name semester Note.P1 Note.P2 Note.P3 gesamt
## 1 1 Mia 3 2.3 2.0 2.7 2.4
## 2 2 Emma 5 2.3 1.3 2.0 2.0
## 3 3 Sofia 9 1.7 1.7 1.7 1.7
## 4 4 Hannah 3 1.7 5.0 1.3 1.8
## 5 5 Emilia 11 2.3 2.3 2.3 2.3
## 6 6 Anna 9 1.3 1.0 1.3 1.2
## 7 7 Marie 9 2.3 1.0 1.7 1.8
## 8 8 Mila 7 1.7 1.0 1.7 1.6
## 9 9 Lina 3 3.3 2.7 5.0 4.0
## 10 10 Lea 9 1.0 2.0 1.3 1.2
## 11 11 Lena 5 1.3 2.3 1.7 1.6
## 12 12 Leonie 3 3.0 1.3 1.7 2.1
## 13 13 Amelie 3 1.7 1.7 1.3 1.5
## 14 14 Luisa 7 2.0 1.0 2.0 1.9
## 15 15 Giuliana 11 1.7 1.0 1.3 1.4
## 16 16 Gloria 11 1.7 2.0 2.3 2.0
## 17 17 Ines 11 2.3 1.0 1.7 1.8
## 18 18 Joy 11 2.7 2.0 3.0 2.7
## 19 19 Youssef 9 2.3 2.3 3.0 2.6
## 20 20 Domenik 9 2.0 5.0 2.3 2.4
## 21 21 Etienne 7 2.7 2.3 1.7 2.1
## 22 22 Jarno 5 2.3 1.7 1.7 1.9
## 23 23 Marian 3 1.7 1.3 1.7 1.6
## 24 24 Mason 11 2.0 1.3 1.7 1.7
## 25 25 Ragnar 7 2.3 1.7 2.0 2.0
## 26 26 Rayan 3 1.7 2.0 5.0 3.3
## 27 27 Semih 7 2.3 2.0 2.0 2.1
read.csv2(file = "datensatz_grades.csv")
## id name semester Note.P1 Note.P2 Note.P3 gesamt
## 1 1 Mia 3 2.3 2.0 2.7 2.4
## 2 2 Emma 5 2.3 1.3 2.0 2.0
## 3 3 Sofia 9 1.7 1.7 1.7 1.7
## 4 4 Hannah 3 1.7 5.0 1.3 1.8
## 5 5 Emilia 11 2.3 2.3 2.3 2.3
## 6 6 Anna 9 1.3 1.0 1.3 1.2
## 7 7 Marie 9 2.3 1.0 1.7 1.8
## 8 8 Mila 7 1.7 1.0 1.7 1.6
## 9 9 Lina 3 3.3 2.7 5.0 4.0
## 10 10 Lea 9 1.0 2.0 1.3 1.2
## 11 11 Lena 5 1.3 2.3 1.7 1.6
## 12 12 Leonie 3 3.0 1.3 1.7 2.1
## 13 13 Amelie 3 1.7 1.7 1.3 1.5
## 14 14 Luisa 7 2.0 1.0 2.0 1.9
## 15 15 Giuliana 11 1.7 1.0 1.3 1.4
## 16 16 Gloria 11 1.7 2.0 2.3 2.0
## 17 17 Ines 11 2.3 1.0 1.7 1.8
## 18 18 Joy 11 2.7 2.0 3.0 2.7
## 19 19 Youssef 9 2.3 2.3 3.0 2.6
## 20 20 Domenik 9 2.0 5.0 2.3 2.4
## 21 21 Etienne 7 2.7 2.3 1.7 2.1
## 22 22 Jarno 5 2.3 1.7 1.7 1.9
## 23 23 Marian 3 1.7 1.3 1.7 1.6
## 24 24 Mason 11 2.0 1.3 1.7 1.7
## 25 25 Ragnar 7 2.3 1.7 2.0 2.0
## 26 26 Rayan 3 1.7 2.0 5.0 3.3
## 27 27 Semih 7 2.3 2.0 2.0 2.1
daten <- read.csv2(file = "datensatz_grades.csv")
Daten von anderen statistischen Sprachen lassen sich meist mit dem Paket foreign einlesen und auch in diesen Formaten abspeichern.
#install.packages(c("openxlsx","foreign"))
library(foreign)
read.spss("datensatz_grades.sav")
## re-encoding from UTF-8
## $id
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## [24] 24 25 26 27
##
## $name
## [1] "Mia " "Emma " "Sofia " "Hannah " "Emilia " "Anna "
## [7] "Marie " "Mila " "Lina " "Lea " "Lena " "Leonie "
## [13] "Amelie " "Luisa " "Giuliana" "Gloria " "Ines " "Joy "
## [19] "Youssef " "Domenik " "Etienne " "Jarno " "Marian " "Mason "
## [25] "Ragnar " "Rayan " "Semih "
##
## $semester
## [1] 3 5 9 3 11 9 9 7 3 9 5 3 3 7 11 11 11 11 9 9 7 5 3
## [24] 11 7 3 7
##
## $NoteP1
## [1] 2.3 2.3 1.7 1.7 2.3 1.3 2.3 1.7 3.3 1.0 1.3 3.0 1.7 2.0 1.7 1.7 2.3
## [18] 2.7 2.3 2.0 2.7 2.3 1.7 2.0 2.3 1.7 2.3
##
## $NoteP2
## [1] 2.0 1.3 1.7 5.0 2.3 1.0 1.0 1.0 2.7 2.0 2.3 1.3 1.7 1.0 1.0 2.0 1.0
## [18] 2.0 2.3 5.0 2.3 1.7 1.3 1.3 1.7 2.0 2.0
##
## $NoteP3
## [1] 2.7 2.0 1.7 1.3 2.3 1.3 1.7 1.7 5.0 1.3 1.7 1.7 1.3 2.0 1.3 2.3 1.7
## [18] 3.0 3.0 2.3 1.7 1.7 1.7 1.7 2.0 5.0 2.0
##
## $gesamt
## [1] 2.4 2.0 1.7 1.8 2.3 1.2 1.8 1.6 4.0 1.2 1.6 2.1 1.5 1.9 1.4 2.0 1.8
## [18] 2.7 2.6 2.4 2.1 1.9 1.6 1.7 2.0 3.3 2.1
##
## attr(,"label.table")
## attr(,"label.table")$id
## NULL
##
## attr(,"label.table")$name
## NULL
##
## attr(,"label.table")$semester
## NULL
##
## attr(,"label.table")$NoteP1
## NULL
##
## attr(,"label.table")$NoteP2
## NULL
##
## attr(,"label.table")$NoteP3
## NULL
##
## attr(,"label.table")$gesamt
## NULL
##
## attr(,"codepage")
## [1] 65001
## attr(,"variable.labels")
## named character(0)
read.dta("datensatz_grades.dta")
## id name semester Note_P1 Note_P2 Note_P3 gesamt
## 1 1 Mia 3 2.3 2.0 2.7 2.4
## 2 2 Emma 5 2.3 1.3 2.0 2.0
## 3 3 Sofia 9 1.7 1.7 1.7 1.7
## 4 4 Hannah 3 1.7 NA 1.3 1.8
## 5 5 Emilia 11 2.3 2.3 2.3 2.3
## 6 6 Anna 9 1.3 1.0 1.3 1.2
## 7 7 Marie 9 2.3 1.0 1.7 1.8
## 8 8 Mila 7 1.7 1.0 1.7 1.6
## 9 9 Lina 3 3.3 2.7 5.0 4.0
## 10 10 Lea 9 1.0 2.0 1.3 1.2
## 11 11 Lena 5 1.3 2.3 1.7 1.6
## 12 12 Leonie 3 3.0 1.3 1.7 2.1
## 13 13 Amelie 3 1.7 1.7 1.3 1.5
## 14 14 Luisa 7 2.0 1.0 2.0 1.9
## 15 15 Giuliana 11 1.7 1.0 1.3 1.4
## 16 16 Gloria 11 1.7 2.0 2.3 2.0
## 17 17 Ines 11 2.3 1.0 1.7 1.8
## 18 18 Joy 11 2.7 2.0 3.0 2.7
## 19 19 Youssef 9 2.3 2.3 3.0 2.6
## 20 20 Domenik 9 2.0 NA 2.3 2.4
## 21 21 Etienne 7 2.7 2.3 1.7 2.1
## 22 22 Jarno 5 2.3 1.7 1.7 1.9
## 23 23 Marian 3 1.7 1.3 1.7 1.6
## 24 24 Mason 11 2.0 1.3 1.7 1.7
## 25 25 Ragnar 7 2.3 1.7 2.0 2.0
## 26 26 Rayan 3 1.7 2.0 5.0 3.3
## 27 27 Semih 7 2.3 2.0 2.0 2.1
Zunächst einmal ist es möglich aus Excel heraus auch CSV-Dateien zu speichern. Arbeitet man also selber erst mit Excel und will seine Daten dann in R einlesen, ist es meistens einfacher, die Datei direkt als CSV zu speichern. Hat man aber eine xlsx-Datei so kann man diese mit den Paketen xlsx oder openxlsx einlesen.
library(openxlsx)
grades <- read.xlsx('datensatz_grades.xlsx', sheet = 1)
grades
## id name semester Note.P1 Note.P2 Note.P3 gesamt
## 1 1 Mia 3 2.3 2.0 2.7 2.4
## 2 2 Emma 5 2.3 1.3 2.0 2.0
## 3 3 Sofia 9 1.7 1.7 1.7 1.7
## 4 4 Hannah 3 1.7 5.0 1.3 1.8
## 5 5 Emilia 11 2.3 2.3 2.3 2.3
## 6 6 Anna 9 1.3 1.0 1.3 1.2
## 7 7 Marie 9 2.3 1.0 1.7 1.8
## 8 8 Mila 7 1.7 1.0 1.7 1.6
## 9 9 Lina 3 3.3 2.7 5.0 4.0
## 10 10 Lea 9 1.0 2.0 1.3 1.2
## 11 11 Lena 5 1.3 2.3 1.7 1.6
## 12 12 Leonie 3 3.0 1.3 1.7 2.1
## 13 13 Amelie 3 1.7 1.7 1.3 1.5
## 14 14 Luisa 7 2.0 1.0 2.0 1.9
## 15 15 Giuliana 11 1.7 1.0 1.3 1.4
## 16 16 Gloria 11 1.7 2.0 2.3 2.0
## 17 17 Ines 11 2.3 1.0 1.7 1.8
## 18 18 Joy 11 2.7 2.0 3.0 2.7
## 19 19 Youssef 9 2.3 2.3 3.0 2.6
## 20 20 Domenik 9 2.0 5.0 2.3 2.4
## 21 21 Etienne 7 2.7 2.3 1.7 2.1
## 22 22 Jarno 5 2.3 1.7 1.7 1.9
## 23 23 Marian 3 1.7 1.3 1.7 1.6
## 24 24 Mason 11 2.0 1.3 1.7 1.7
## 25 25 Ragnar 7 2.3 1.7 2.0 2.0
## 26 26 Rayan 3 1.7 2.0 5.0 3.3
## 27 27 Semih 7 2.3 2.0 2.0 2.1
…
summary(grades)
## id name semester Note.P1
## Min. : 1.0 Length:27 Min. : 3.000 Min. :1.000
## 1st Qu.: 7.5 Class :character 1st Qu.: 4.000 1st Qu.:1.700
## Median :14.0 Mode :character Median : 7.000 Median :2.000
## Mean :14.0 Mean : 7.074 Mean :2.059
## 3rd Qu.:20.5 3rd Qu.: 9.000 3rd Qu.:2.300
## Max. :27.0 Max. :11.000 Max. :3.300
## Note.P2 Note.P3 gesamt
## Min. :1.000 Min. :1.300 Min. :1.200
## 1st Qu.:1.300 1st Qu.:1.700 1st Qu.:1.650
## Median :1.700 Median :1.700 Median :1.900
## Mean :1.922 Mean :2.115 Mean :2.026
## 3rd Qu.:2.150 3rd Qu.:2.300 3rd Qu.:2.200
## Max. :5.000 Max. :5.000 Max. :4.000
summary(grades$Note.P1)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.000 1.700 2.000 2.059 2.300 3.300
table(grades$Note.P1)
##
## 1 1.3 1.7 2 2.3 2.7 3 3.3
## 1 2 8 3 9 2 1 1
table(grades$Note.P1, grades$Note.P2)
##
## 1 1.3 1.7 2 2.3 2.7 5
## 1 0 0 0 1 0 0 0
## 1.3 1 0 0 0 1 0 0
## 1.7 2 1 2 2 0 0 1
## 2 1 1 0 0 0 0 1
## 2.3 2 1 2 2 2 0 0
## 2.7 0 0 0 1 1 0 0
## 3 0 1 0 0 0 0 0
## 3.3 0 0 0 0 0 1 0
semester_neuerKurs <- c(7,3,5,5,5,5,7,5,3,7,5,5,11,7,5)
t.test(grades$semester, semester_neuerKurs, paired = F)
##
## Welch Two Sample t-test
##
## data: grades$semester and semester_neuerKurs
## t = 1.8149, df = 39.101, p-value = 0.07721
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -0.160976 2.975791
## sample estimates:
## mean of x mean of y
## 7.074074 5.666667
t.test(grades$,y2,paired=TRUE)
cor(grades$Note.P1, grades$Note.P3)
## [1] 0.4275219
cor.test(grades$Note.P1, grades$Note.P3)
##
## Pearson's product-moment correlation
##
## data: grades$Note.P1 and grades$Note.P3
## t = 2.3646, df = 25, p-value = 0.02612
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## 0.05672353 0.69467587
## sample estimates:
## cor
## 0.4275219
grades$gesamt_round <- round(grades$gesamt,0)
grades$P1_round <- round(grades$Note.P1,0)
table(grades$P1_round, grades$gesamt_round)
##
## 1 2 3 4
## 1 2 1 0 0
## 2 1 17 2 0
## 3 0 2 1 1
chisq.test(grades$P1_round, grades$gesamt_round)
## Warning in chisq.test(grades$P1_round, grades$gesamt_round): Chi-squared
## approximation may be incorrect
##
## Pearson's Chi-squared test
##
## data: grades$P1_round and grades$gesamt_round
## X-squared = 17.558, df = 6, p-value = 0.007439
#install.packages("lsr")
library(lsr)
cramersV(table(grades$P1_round, grades$gesamt_round))
## Warning in chisq.test(...): Chi-squared approximation may be incorrect
## [1] 0.5702095
plot(grades$Note.P1, grades$gesamt)
model1 <- lm(formula = grades$gesamt ~ grades$Note.P1)
summary(model1)
##
## Call:
## lm(formula = grades$gesamt ~ grades$Note.P1)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.6507 -0.2647 -0.1114 0.1697 1.5509
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.4394 0.3721 1.181 0.248726
## grades$Note.P1 0.7704 0.1754 4.393 0.000179 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4668 on 25 degrees of freedom
## Multiple R-squared: 0.4357, Adjusted R-squared: 0.4131
## F-statistic: 19.3 on 1 and 25 DF, p-value: 0.0001795
model2 <- lm(formula = grades$gesamt ~ grades$Note.P1 + grades$Note.P2 + grades$Note.P3)
summary(model2)
##
## Call:
## lm(formula = grades$gesamt ~ grades$Note.P1 + grades$Note.P2 +
## grades$Note.P3)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.040234 -0.017022 -0.005735 0.011373 0.052015
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.001948 0.023955 0.081 0.936
## grades$Note.P1 0.381246 0.011428 33.361 < 2e-16 ***
## grades$Note.P2 0.104044 0.005384 19.325 1.02e-15 ***
## grades$Note.P3 0.491247 0.006349 77.380 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.02744 on 23 degrees of freedom
## Multiple R-squared: 0.9982, Adjusted R-squared: 0.998
## F-statistic: 4264 on 3 and 23 DF, p-value: < 2.2e-16
Statt komplizierte Klammerstrukturen zu nutzen oder nach jedem Schritt das Objekt neu abzuspeichern, ist es durch das magittr-package möglich sogenannte pipes zu nutzen. Durch das dplyr-Paket wurden pipes zu einer besonderen Innovation und ändern den workflow in R. Oft wird dadurch der Code sehr viel einfacher lesbar. Durch eine pipe (%>%) lassen sich Ergebnisse aus dem einen Befehl, direkt in den nächsten “überführen”.
s1 <- 3+6
s2 <- exp(s1)
s3 <- round(s2, 3)
s4 <- s3 > 1000
# oder
t <- round(exp((3+6)),3) > 1000
# unkomplizierter
u <- (3+6) %>%
exp() %>%
round(.,3) > 1000
logical operators “==” nicht “=” aus gapminder wird nichts entfernt, sondern der filter nur onscreen ausgegeben Inhalt mit Text mit Anführungsstrichen
Multiple conditions mit Komma
gapminder[gapminder$year==2007, ]
## # A tibble: 142 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 2007 43.8 31889923 975.
## 2 Albania Europe 2007 76.4 3600523 5937.
## 3 Algeria Africa 2007 72.3 33333216 6223.
## 4 Angola Africa 2007 42.7 12420476 4797.
## 5 Argentina Americas 2007 75.3 40301927 12779.
## 6 Australia Oceania 2007 81.2 20434176 34435.
## 7 Austria Europe 2007 79.8 8199783 36126.
## 8 Bahrain Asia 2007 75.6 708573 29796.
## 9 Bangladesh Asia 2007 64.1 150448339 1391.
## 10 Belgium Europe 2007 79.4 10392226 33693.
## # ... with 132 more rows
gapminder %>%
filter(year == 2007)
## # A tibble: 142 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 2007 43.8 31889923 975.
## 2 Albania Europe 2007 76.4 3600523 5937.
## 3 Algeria Africa 2007 72.3 33333216 6223.
## 4 Angola Africa 2007 42.7 12420476 4797.
## 5 Argentina Americas 2007 75.3 40301927 12779.
## 6 Australia Oceania 2007 81.2 20434176 34435.
## 7 Austria Europe 2007 79.8 8199783 36126.
## 8 Bahrain Asia 2007 75.6 708573 29796.
## 9 Bangladesh Asia 2007 64.1 150448339 1391.
## 10 Belgium Europe 2007 79.4 10392226 33693.
## # ... with 132 more rows
gapminder %>%
filter(country == "United States")
## # A tibble: 12 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 United States Americas 1952 68.4 157553000 13990.
## 2 United States Americas 1957 69.5 171984000 14847.
## 3 United States Americas 1962 70.2 186538000 16173.
## 4 United States Americas 1967 70.8 198712000 19530.
## 5 United States Americas 1972 71.3 209896000 21806.
## 6 United States Americas 1977 73.4 220239000 24073.
## 7 United States Americas 1982 74.6 232187835 25010.
## 8 United States Americas 1987 75.0 242803533 29884.
## 9 United States Americas 1992 76.1 256894189 32004.
## 10 United States Americas 1997 76.8 272911760 35767.
## 11 United States Americas 2002 77.3 287675526 39097.
## 12 United States Americas 2007 78.2 301139947 42952.
gapminder %>%
filter(year == 2007, country == "United States")
## # A tibble: 1 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 United States Americas 2007 78.2 301139947 42952.
Select specific variables (columns) by name. No need for complicated counting or concatenating by with c() and square brackets. You can select ranges of variables using “:”. Use the “-” to drop columns. You can change the order, in which the variables appear in the data frame. You can also select and renaming variables at the same time.
gapminder
## # A tibble: 1,704 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
## 7 Afghanistan Asia 1982 39.9 12881816 978.
## 8 Afghanistan Asia 1987 40.8 13867957 852.
## 9 Afghanistan Asia 1992 41.7 16317921 649.
## 10 Afghanistan Asia 1997 41.8 22227415 635.
## # ... with 1,694 more rows
gapminder %>%
select(country, year, lifeExp)
## # A tibble: 1,704 x 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Afghanistan 1952 28.8
## 2 Afghanistan 1957 30.3
## 3 Afghanistan 1962 32.0
## 4 Afghanistan 1967 34.0
## 5 Afghanistan 1972 36.1
## 6 Afghanistan 1977 38.4
## 7 Afghanistan 1982 39.9
## 8 Afghanistan 1987 40.8
## 9 Afghanistan 1992 41.7
## 10 Afghanistan 1997 41.8
## # ... with 1,694 more rows
gapminder %>%
select(country, lifeExp:gdpPercap)
## # A tibble: 1,704 x 4
## country lifeExp pop gdpPercap
## <fct> <dbl> <int> <dbl>
## 1 Afghanistan 28.8 8425333 779.
## 2 Afghanistan 30.3 9240934 821.
## 3 Afghanistan 32.0 10267083 853.
## 4 Afghanistan 34.0 11537966 836.
## 5 Afghanistan 36.1 13079460 740.
## 6 Afghanistan 38.4 14880372 786.
## 7 Afghanistan 39.9 12881816 978.
## 8 Afghanistan 40.8 13867957 852.
## 9 Afghanistan 41.7 16317921 649.
## 10 Afghanistan 41.8 22227415 635.
## # ... with 1,694 more rows
gapminder %>%
select(-continent)
## # A tibble: 1,704 x 5
## country year lifeExp pop gdpPercap
## <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan 1952 28.8 8425333 779.
## 2 Afghanistan 1957 30.3 9240934 821.
## 3 Afghanistan 1962 32.0 10267083 853.
## 4 Afghanistan 1967 34.0 11537966 836.
## 5 Afghanistan 1972 36.1 13079460 740.
## 6 Afghanistan 1977 38.4 14880372 786.
## 7 Afghanistan 1982 39.9 12881816 978.
## 8 Afghanistan 1987 40.8 13867957 852.
## 9 Afghanistan 1992 41.7 16317921 649.
## 10 Afghanistan 1997 41.8 22227415 635.
## # ... with 1,694 more rows
gapminder %>%
select(continent, country, year:gdpPercap) #switch continent and country
## # A tibble: 1,704 x 6
## continent country year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Asia Afghanistan 1952 28.8 8425333 779.
## 2 Asia Afghanistan 1957 30.3 9240934 821.
## 3 Asia Afghanistan 1962 32.0 10267083 853.
## 4 Asia Afghanistan 1967 34.0 11537966 836.
## 5 Asia Afghanistan 1972 36.1 13079460 740.
## 6 Asia Afghanistan 1977 38.4 14880372 786.
## 7 Asia Afghanistan 1982 39.9 12881816 978.
## 8 Asia Afghanistan 1987 40.8 13867957 852.
## 9 Asia Afghanistan 1992 41.7 16317921 649.
## 10 Asia Afghanistan 1997 41.8 22227415 635.
## # ... with 1,694 more rows
gapminder %>%
select(kontinent = continent, land = country, jahr = year)
## # A tibble: 1,704 x 3
## kontinent land jahr
## <fct> <fct> <int>
## 1 Asia Afghanistan 1952
## 2 Asia Afghanistan 1957
## 3 Asia Afghanistan 1962
## 4 Asia Afghanistan 1967
## 5 Asia Afghanistan 1972
## 6 Asia Afghanistan 1977
## 7 Asia Afghanistan 1982
## 8 Asia Afghanistan 1987
## 9 Asia Afghanistan 1992
## 10 Asia Afghanistan 1997
## # ... with 1,694 more rows
gapminder %>%
arrange(gdpPercap)
## # A tibble: 1,704 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Congo, Dem. Rep. Africa 2002 45.0 55379852 241.
## 2 Congo, Dem. Rep. Africa 2007 46.5 64606759 278.
## 3 Lesotho Africa 1952 42.1 748747 299.
## 4 Guinea-Bissau Africa 1952 32.5 580653 300.
## 5 Congo, Dem. Rep. Africa 1997 42.6 47798986 312.
## 6 Eritrea Africa 1952 35.9 1438760 329.
## 7 Myanmar Asia 1952 36.3 20092996 331
## 8 Lesotho Africa 1957 45.0 813338 336.
## 9 Burundi Africa 1952 39.0 2445618 339.
## 10 Eritrea Africa 1957 38.0 1542611 344.
## # ... with 1,694 more rows
gapminder %>%
arrange(desc(gdpPercap))
## # A tibble: 1,704 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Kuwait Asia 1957 58.0 212846 113523.
## 2 Kuwait Asia 1972 67.7 841934 109348.
## 3 Kuwait Asia 1952 55.6 160000 108382.
## 4 Kuwait Asia 1962 60.5 358266 95458.
## 5 Kuwait Asia 1967 64.6 575003 80895.
## 6 Kuwait Asia 1977 69.3 1140357 59265.
## 7 Norway Europe 2007 80.2 4627926 49357.
## 8 Kuwait Asia 2007 77.6 2505559 47307.
## 9 Singapore Asia 2007 80.0 4553009 47143.
## 10 Norway Europe 2002 79.0 4535591 44684.
## # ... with 1,694 more rows
gapminder %>%
arrange(year, gdpPercap)
## # A tibble: 1,704 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Lesotho Africa 1952 42.1 748747 299.
## 2 Guinea-Bissau Africa 1952 32.5 580653 300.
## 3 Eritrea Africa 1952 35.9 1438760 329.
## 4 Myanmar Asia 1952 36.3 20092996 331
## 5 Burundi Africa 1952 39.0 2445618 339.
## 6 Ethiopia Africa 1952 34.1 20860941 362.
## 7 Cambodia Asia 1952 39.4 4693836 368.
## 8 Malawi Africa 1952 36.3 2917802 369.
## 9 Equatorial Guinea Africa 1952 34.5 216964 376.
## 10 China Asia 1952 44 556263527 400.
## # ... with 1,694 more rows
existing and new variables
gapminder %>%
mutate(pop_mio = pop / 1000000)
## # A tibble: 1,704 x 7
## country continent year lifeExp pop gdpPercap pop_mio
## <fct> <fct> <int> <dbl> <int> <dbl> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779. 8.43
## 2 Afghanistan Asia 1957 30.3 9240934 821. 9.24
## 3 Afghanistan Asia 1962 32.0 10267083 853. 10.3
## 4 Afghanistan Asia 1967 34.0 11537966 836. 11.5
## 5 Afghanistan Asia 1972 36.1 13079460 740. 13.1
## 6 Afghanistan Asia 1977 38.4 14880372 786. 14.9
## 7 Afghanistan Asia 1982 39.9 12881816 978. 12.9
## 8 Afghanistan Asia 1987 40.8 13867957 852. 13.9
## 9 Afghanistan Asia 1992 41.7 16317921 649. 16.3
## 10 Afghanistan Asia 1997 41.8 22227415 635. 22.2
## # ... with 1,694 more rows
total GDP now spaces only one word
gapminder %>%
mutate(gdp = gdpPercap * pop)
## # A tibble: 1,704 x 7
## country continent year lifeExp pop gdpPercap gdp
## <fct> <fct> <int> <dbl> <int> <dbl> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779. 6567086330.
## 2 Afghanistan Asia 1957 30.3 9240934 821. 7585448670.
## 3 Afghanistan Asia 1962 32.0 10267083 853. 8758855797.
## 4 Afghanistan Asia 1967 34.0 11537966 836. 9648014150.
## 5 Afghanistan Asia 1972 36.1 13079460 740. 9678553274.
## 6 Afghanistan Asia 1977 38.4 14880372 786. 11697659231.
## 7 Afghanistan Asia 1982 39.9 12881816 978. 12598563401.
## 8 Afghanistan Asia 1987 40.8 13867957 852. 11820990309.
## 9 Afghanistan Asia 1992 41.7 16317921 649. 10595901589.
## 10 Afghanistan Asia 1997 41.8 22227415 635. 14121995875.
## # ... with 1,694 more rows
…
Natürlich kann man die kompletten Ketten auch in einem neuen Objekt sichern.
gapminder2 <- gapminder %>%
mutate(gdp = gdpPercap * pop) %>%
arrange(gdp)
gapminder2
## # A tibble: 1,704 x 7
## country continent year lifeExp pop gdpPercap gdp
## <fct> <fct> <int> <dbl> <int> <dbl> <dbl>
## 1 Sao Tome and Princi~ Africa 1952 46.5 60011 880. 5.28e7
## 2 Sao Tome and Princi~ Africa 1957 48.9 61325 861. 5.28e7
## 3 Sao Tome and Princi~ Africa 1962 51.9 65345 1072. 7.00e7
## 4 Equatorial Guinea Africa 1952 34.5 216964 376. 8.15e7
## 5 Sao Tome and Princi~ Africa 1967 54.4 70787 1385. 9.80e7
## 6 Equatorial Guinea Africa 1957 36.0 232922 426. 9.92e7
## 7 Sao Tome and Princi~ Africa 1972 56.5 76595 1533. 1.17e8
## 8 Gambia Africa 1952 30 284320 485. 1.38e8
## 9 Equatorial Guinea Africa 1962 37.5 249220 583. 1.45e8
## 10 Sao Tome and Princi~ Africa 1977 58.6 86796 1738. 1.51e8
## # ... with 1,694 more rows
many rows into one
gapminder %>%
summarize(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
## meanLifeExp
## <dbl>
## 1 59.5
“mean()” ist eine built-in Funktion. Hier logischerweise der Mittelwert. R hat einige solcher built-in Funktionen, die man sich nicht selber schreiben muss
Beispiele bringen:
Eigentlich natürlich keinen Sinn den Mittelwert über alles zu machen
gapminder %>%
filter(year == 2007) %>%
summarise(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
## meanLifeExp
## <dbl>
## 1 67.0
mehrere Spalten (Variablen gleichzeitig)
gapminder %>%
filter(year == 2007) %>%
summarise(meanLifeExp = mean(lifeExp),
totalPop = sum(as.numeric(pop)))
## # A tibble: 1 x 2
## meanLifeExp totalPop
## <dbl> <dbl>
## 1 67.0 6251013179
Ich möchte nicht die LifeExpectancy oder Population über alle Länder und alle Zeitpunkte Daher gruppiere ich den Datensatz in verschiedene Teile, basierend auf der Variable “year”
gapminder %>%
group_by(year) %>%
summarize(meanLifeExp = mean(lifeExp),
totalPop = sum(pop))
Produziert bei mir Fehler (integer overflow), deshalb wie in Fehlermeldung vorgeschlagen “as.integer”. Innerhalb der Funktionen, lassen sich also wieder weitere Funktionen verschachteln
gapminder_3 <- gapminder %>%
group_by(year) %>%
summarize(meanLifeExp = mean(lifeExp),
totalPop = sum(as.integer(pop)))
Jetzt finde ich das auch nicht besonders aussagekräftig. Bei dem Durchschnitt sind alle Ländern mit drin. Deshalb filtern nur für das Jahr 2007 und anschließend nach Kontinent.
gapminder %>%
filter(year == 2007) %>%
group_by(continent) %>%
summarize(meanLifeExp = mean(lifeExp),
totalPop = sum(as.numeric(pop)))
## # A tibble: 5 x 3
## continent meanLifeExp totalPop
## <fct> <dbl> <dbl>
## 1 Africa 54.8 929539692
## 2 Americas 73.6 898871184
## 3 Asia 70.7 3811953827
## 4 Europe 77.6 586098529
## 5 Oceania 80.7 24549947
Jetzt wollen wir aber jeweils den Durchschnitt für alle Jahr und alle Kontinente. group_by lässt sich auch mit mehreren Variablen nutzen. Gruppierung nach mehreren Variablen.
gapminder %>%
group_by(year, continent) %>%
summarize(totalPop = sum(as.integer(pop)),
meanLifeExp = mean(lifeExp))
## # A tibble: 60 x 4
## # Groups: year [?]
## year continent totalPop meanLifeExp
## <int> <fct> <dbl> <dbl>
## 1 1952 Africa 237640501 39.1
## 2 1952 Americas 345152446 53.3
## 3 1952 Asia 1395357351 46.3
## 4 1952 Europe 418120846 64.4
## 5 1952 Oceania 10686006 69.3
## 6 1957 Africa 264837738 41.3
## 7 1957 Americas 386953916 56.0
## 8 1957 Asia 1562780599 49.3
## 9 1957 Europe 437890351 66.7
## 10 1957 Oceania 11941976 70.3
## # ... with 50 more rows
Nach summarise ist die Gruppierung aufgehoben.
gapminder %>%
group_by(year, continent) %>%
summarize(totalPop = sum(as.integer(pop)),
meanLifeExp = mean(lifeExp)) %>%
arrange(desc(totalPop))
## # A tibble: 60 x 4
## # Groups: year [12]
## year continent totalPop meanLifeExp
## <int> <fct> <dbl> <dbl>
## 1 2007 Asia 3811953827 70.7
## 2 2002 Asia 3601802203 69.2
## 3 1997 Asia 3383285500 68.0
## 4 1992 Asia 3133292191 66.5
## 5 1987 Asia 2871220762 64.9
## 6 1982 Asia 2610135582 62.6
## 7 1977 Asia 2384513556 59.6
## 8 1972 Asia 2150972248 57.3
## 9 1967 Asia 1905662900 54.7
## 10 1962 Asia 1696357182 51.6
## # ... with 50 more rows
Wenn ich aber zB arrange direkt nach group_by ausführe, dann werden die Gruppen weiter berücksichtigt -> Sortierung innerhalb von Gruppen.
gapminder %>%
group_by(year, continent) %>%
arrange(desc(pop))
## # A tibble: 1,704 x 6
## # Groups: year, continent [60]
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 China Asia 2007 73.0 1318683096 4959.
## 2 China Asia 2002 72.0 1280400000 3119.
## 3 China Asia 1997 70.4 1230075000 2289.
## 4 China Asia 1992 68.7 1164970000 1656.
## 5 India Asia 2007 64.7 1110396331 2452.
## 6 China Asia 1987 67.3 1084035000 1379.
## 7 India Asia 2002 62.9 1034172547 1747.
## 8 China Asia 1982 65.5 1000281000 962.
## 9 India Asia 1997 61.8 959000000 1459.
## 10 China Asia 1977 64.0 943455000 741.
## # ... with 1,694 more rows
Durch anschließen von ungroup() kann ich die Gruppierung wieder aufheben.
asdasd
library(ggplot2)
ggplot2 von Hadley Wickham auch hier eine eigene “Grammatik” Modular aufgebaut (Bedeutet was? - add a layer)
Ein neuer Datensatz wurde durch erstellt: gapminder_2007. Durch die filter-Funktion enthält er nur die Daten aus dem Jahr 2007.
gapminder_2007
## # A tibble: 142 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 2007 43.8 31889923 975.
## 2 Albania Europe 2007 76.4 3600523 5937.
## 3 Algeria Africa 2007 72.3 33333216 6223.
## 4 Angola Africa 2007 42.7 12420476 4797.
## 5 Argentina Americas 2007 75.3 40301927 12779.
## 6 Australia Oceania 2007 81.2 20434176 34435.
## 7 Austria Europe 2007 79.8 8199783 36126.
## 8 Bahrain Asia 2007 75.6 708573 29796.
## 9 Bangladesh Asia 2007 64.1 150448339 1391.
## 10 Belgium Europe 2007 79.4 10392226 33693.
## # ... with 132 more rows
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
geom_point()
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
geom_point()
Problem: Viele Länder am linken Rand, mit sehr geringem gdpPercap Lösungsmöglichkeit: Log Scale (Modularer Aufbau - Hinzufügen eines “Moduls” log_scale)
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
geom_point()+
scale_x_log10()
ggplot(gapminder_2007, aes(x = pop, y = gdpPercap))+
geom_point()+
scale_x_log10()+
scale_y_log10()
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
geom_point()+
scale_x_log10()+
geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Bisher hatten wir nur x und y Mit aesthetics (aes) lassen sich aber auch noch mehr Merkmale kontrollieren Farbe, Gruppen, Punktgröße etc.
Automatisches Hinzufügen der Legende
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent)) +
geom_point() +
scale_x_log10()
Notes: Zweite Zeile bei size, macht dem Code nichts aus. Nach Kommata wird sogar einigermaßen schön eingerückt
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, color = continent,
size = pop)) +
geom_point() +
scale_x_log10()
Unterteilung in “Untergrafiken”, unterteilt nach einer bestimmten Kategorie
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
geom_point() +
scale_x_log10() +
facet_wrap(~ continent)
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent, size = pop))+
geom_point()+
scale_x_log10()+
facet_wrap(~ year)
Neues Objekt (Datensatz speichern): gapminder gruppert nach Jahr und die Population und durchschnittliche Lebenserwartung pro Jahr zusammengefasst.
by_year <- gapminder %>%
group_by(year) %>%
summarize(totalPop = sum(as.integer(pop)),
meanLifeExp = mean(lifeExp))
by_year
## # A tibble: 12 x 3
## year totalPop meanLifeExp
## <int> <dbl> <dbl>
## 1 1952 2406957150 49.1
## 2 1957 2664404580 51.5
## 3 1962 2899782974 53.6
## 4 1967 3217478384 55.7
## 5 1972 3576977158 57.6
## 6 1977 3930045807 59.6
## 7 1982 4289436840 61.5
## 8 1987 4691477418 63.2
## 9 1992 5110710260 64.2
## 10 1997 5515204472 65.0
## 11 2002 5886977579 65.7
## 12 2007 6251013179 67.0
ggplot(by_year, aes(x = year, y = totalPop)) +
geom_point()
Hier enthält die y-Achse nicht die 0 (Meistens großer Fehler). Wir müssen deshalb die Skala bearbeiten und anpassen. Wieder kann dies durch ein neues “Modul” passieren.
ggplot(by_year, aes(x = year, y = totalPop)) +
geom_point() +
expand_limits(y = 0)
Neues Objekt (Datensatz) mit einer Gruppierung nach Year und continent.
by_year_continent <- gapminder %>%
group_by(year, continent) %>%
summarize(totalPop = sum(as.numeric(pop)),
meanLifeExp = mean(lifeExp))
by_year_continent
## # A tibble: 60 x 4
## # Groups: year [?]
## year continent totalPop meanLifeExp
## <int> <fct> <dbl> <dbl>
## 1 1952 Africa 237640501 39.1
## 2 1952 Americas 345152446 53.3
## 3 1952 Asia 1395357351 46.3
## 4 1952 Europe 418120846 64.4
## 5 1952 Oceania 10686006 69.3
## 6 1957 Africa 264837738 41.3
## 7 1957 Americas 386953916 56.0
## 8 1957 Asia 1562780599 49.3
## 9 1957 Europe 437890351 66.7
## 10 1957 Oceania 11941976 70.3
## # ... with 50 more rows
Durch Farbe können wir wieder die verschiedenen Kontinenten voneinander trennen.
ggplot(by_year_continent, aes(x = year, y = totalPop, color = continent)) +
geom_point() +
expand_limits(y = 0)
Bisher nur “Scatterplots”, mit geom_point(). Jede Menge andere Varianten ebenso möglich. Wahl des Graphen abhängig von dem Skalenniveau der Daten und dem Ziel, was die Grafik zeigen soll.
ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
geom_point() +
expand_limits(y = 0)
ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
geom_line() +
expand_limits(y = 0)
Man kann aber auch mehrere Graphtypen miteinander verbinden. Wieder durch die modulare “Grammatik” des Pakets.
ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
geom_line() +
geom_point() +
expand_limits(y = 0)
Neuer Datensatz mit der durchschnittlichen Lebenserwartung pro Kontinent für das Jahr 2007
by_continent <- gapminder %>%
filter(year == 2007) %>%
group_by(continent) %>%
summarize(meanLifeExp = mean(lifeExp))
by_continent
## # A tibble: 5 x 2
## continent meanLifeExp
## <fct> <dbl>
## 1 Africa 54.8
## 2 Americas 73.6
## 3 Asia 70.7
## 4 Europe 77.6
## 5 Oceania 80.7
Unerwarterweise nicht geom_bar. Das gibts aber auch. Hier geom_col. Bei geom_bar könnte man das gleiche Ergebnis erreichen, müsste aber noch zusätzliche Argumente anfügen.
ggplot(by_continent, aes(x = continent, y = meanLifeExp)) +
geom_col()
Nur ein “aesthetic”. Die x-Variable. Die Anzahl pro Balken rechnet R dann selber aus. Auch die Breite der Balken wir selbst optimiert. Diese kann man aber anpassen.
ggplot(gapminder_2007, aes(x = lifeExp)) +
geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
ggplot(gapminder_2007, aes(x = lifeExp)) +
geom_histogram(binwidth = 5)
Compare distributions across continents.
Black Line: Median, Box: 25% and 75%. Half of the distribution inside the box. whiskers: Additional countries Dots: Outliers (out of 95%)
ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) +
geom_point()
ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) +
geom_boxplot()
ggplot(gapminder_2007, aes(x = continent, y = gdpPercap)) +
geom_boxplot() +
scale_y_log10() +
labs(title = "Comparing GDP per capita across continents",
x = "Continent",
y = "GDP per capita")
“Reguläre Ausdrücke” sind eine Art Sprache, die beim Programmieren für diverse Problemlösungen verwendet werden kann, insbesondere dann, wenn es darum geht, Zeichenketten (Strings) zu bearbeiten, zu prüfen oder in ihnen etwas zu suchen. Und weil der Name “Reguläre Ausdrücke” etwas unhandlich ist, heißen die “Regular Expressions” auch oft einfach nur “RegEx”.
cntr <- unique(gapminder$country)
## Alle Länder die ein O am Ende haben
cntr[grep(pattern = "[o]", x = cntr)] ## Reicht nicht.
## [1] Angola Bolivia Bosnia and Herzegovina
## [4] Botswana Burkina Faso Cambodia
## [7] Cameroon Colombia Comoros
## [10] Congo, Dem. Rep. Congo, Rep. Costa Rica
## [13] Cote d'Ivoire Croatia Djibouti
## [16] Dominican Republic Ecuador El Salvador
## [19] Equatorial Guinea Ethiopia Gabon
## [22] Honduras Hong Kong, China Indonesia
## [25] Jordan Korea, Dem. Rep. Korea, Rep.
## [28] Lebanon Lesotho Mexico
## [31] Mongolia Montenegro Morocco
## [34] Mozambique Norway Poland
## [37] Portugal Puerto Rico Reunion
## [40] Romania Sao Tome and Principe Sierra Leone
## [43] Singapore Slovak Republic Slovenia
## [46] Somalia South Africa Togo
## [49] Trinidad and Tobago United Kingdom
## 142 Levels: Afghanistan Albania Algeria Angola Argentina ... Zimbabwe
cntr[grep(pattern = "[o$]", x = cntr)] ## innerhalb von regex matched das $-Zeichen das Ende einer Zeile
## [1] Angola Bolivia Bosnia and Herzegovina
## [4] Botswana Burkina Faso Cambodia
## [7] Cameroon Colombia Comoros
## [10] Congo, Dem. Rep. Congo, Rep. Costa Rica
## [13] Cote d'Ivoire Croatia Djibouti
## [16] Dominican Republic Ecuador El Salvador
## [19] Equatorial Guinea Ethiopia Gabon
## [22] Honduras Hong Kong, China Indonesia
## [25] Jordan Korea, Dem. Rep. Korea, Rep.
## [28] Lebanon Lesotho Mexico
## [31] Mongolia Montenegro Morocco
## [34] Mozambique Norway Poland
## [37] Portugal Puerto Rico Reunion
## [40] Romania Sao Tome and Principe Sierra Leone
## [43] Singapore Slovak Republic Slovenia
## [46] Somalia South Africa Togo
## [49] Trinidad and Tobago United Kingdom
## 142 Levels: Afghanistan Albania Algeria Angola Argentina ... Zimbabwe
cntr[grep(pattern = "[[:punct:]]", x = cntr)] # alle punctuation characters
## [1] Congo, Dem. Rep. Congo, Rep. Cote d'Ivoire Guinea-Bissau
## [5] Hong Kong, China Korea, Dem. Rep. Korea, Rep. Yemen, Rep.
## 142 Levels: Afghanistan Albania Algeria Angola Argentina ... Zimbabwe
names <- c("anna","crissy","puerto","cristian","garcia","steven","alex","rudy")
#doesn't matter if e is a match
grep(pattern = "e*",x = names,value = T)
## [1] "anna" "crissy" "puerto" "cristian" "garcia" "steven"
## [7] "alex" "rudy"
#must match t one or more times
grep(pattern = "t+",x = names,value = T)
## [1] "puerto" "cristian" "steven"
#must match n two times
grep(pattern = "n{2}",x = names,value = T)
## [1] "anna"
Internetseiten verwenden verschiedene Sprachen für die Seitenbeschreibung, dahinterliegende Datenbanken etc. Diese sind meistens baumartig aufgebaut. Das bedeutet, dass von einem Knotenpunkt mehrere “Äste” abgehen können und ihrerseits wieder Äste bilden. Jedes Blatt (Element) ist dadurch aber eindeutig einem bestimmten Weg von Ästen bis zum Stamm zuzuordnen. Durch diesen Weg kann man navigieren, da jeder Knoten weiß welche Äste er hat und umgekehrt.
siehe Datacamp-pdf S. 20ff
Im Paket rvest geht diese Navigation über “parents” und “children” oder direkt konkrete Schlüsselwörter.
Beispiel: Links auf Wahlseite des Bundeswahlleiters.
library(plyr)
## -------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## -------------------------------------------------------------------------
##
## Attaching package: 'plyr'
## The following objects are masked from 'package:dplyr':
##
## arrange, count, desc, failwith, id, mutate, rename, summarise,
## summarize
## The following object is masked from 'package:purrr':
##
## compact
library(dplyr)
library(rvest)
## Loading required package: xml2
##
## Attaching package: 'rvest'
## The following object is masked from 'package:purrr':
##
## pluck
## The following object is masked from 'package:readr':
##
## guess_encoding
library(stringr)
url <- "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99.html"
webpage <- read_html(url)
#Erstelle Liste von Bundesland-Links
bl_url_list <- html_nodes(webpage, '.linklist') %>%
html_nodes('a') %>% # alle Knoten die Links sind
html_attr("href") %>% # Bei den Knoten will man nur den wirklichen Link (keinen Linktext oder andere Arguemente)
.[grep(".html",.)] %>% # nur welche die auf HTML enden
paste0("https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/",.) #abschließend noch den Rest davor
bl_url_list
## [1] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-8.html"
## [2] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-9.html"
## [3] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-11.html"
## [4] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-12.html"
## [5] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-4.html"
## [6] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-2.html"
## [7] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-6.html"
## [8] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-13.html"
## [9] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-3.html"
## [10] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-5.html"
## [11] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-7.html"
## [12] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-10.html"
## [13] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-14.html"
## [14] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-15.html"
## [15] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-1.html"
## [16] "https://www.bundeswahlleiter.de/bundestagswahlen/2017/ergebnisse/bund-99/land-16.html"
### ALTERNATIV über children
html_nodes(webpage, '.linklist') %>%
.[2] %>%
html_children() %>%
html_children() %>%
html_attr("href")
## [1] "bund-99/land-8.html" "bund-99/land-9.html" "bund-99/land-11.html"
## [4] "bund-99/land-12.html" "bund-99/land-4.html" "bund-99/land-2.html"
## [7] "bund-99/land-6.html" "bund-99/land-13.html" "bund-99/land-3.html"
## [10] "bund-99/land-5.html" "bund-99/land-7.html" "bund-99/land-10.html"
## [13] "bund-99/land-14.html" "bund-99/land-15.html" "bund-99/land-1.html"
## [16] "bund-99/land-16.html"